<?php

namespace App\Http\Controllers\Admin;

use App\Models\User\LiveScoreWater;
use App\Models\User\LiveUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $search     = trim($request->input('search',''));
        $data       = LiveUser::getUserList($start_time,$end_time,$search,0);
        return self::response($data,'200');
    }

    public function changeStatus(Request $request)
    {
        $id     = (int)$request->input('id');
        $status = (int)$request->input('status');
        if (empty($id)) {
            return self::response(null,-1,'用户ID不能为空');
        }
        $flag = LiveUser::changeStatusById($id,$status);
        if (!$flag) {
            return self::response(null,-2,'修改失败，请稍后再试哦~');
        }
        return self::response(null,'200');
    }

    public function delete(Request $request)
    {
        $id     = (int)$request->input('id');
        if (empty($id)) {
            return self::response(null,-1,'用户ID不能为空');
        }
        $flag = LiveUser::deleteUserById($id);
        if (!$flag) {
            return self::response(null,-2,'删除失败，请稍后再试哦~');
        }
        return self::response(null,'200');
    }

    public function addUser(Request $request)
    {
        $name       = $request->input('name');
        $password   = $request->input('password');
        $sex        = (int)$request->input('sex');
        $status     = (int)$request->input('status',1);
        $avatar     = $request->input('avatar','');
        if (empty($name)) {
            return self::response(null,'-1','用户名为空');
        }
        if (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u',$name)) {
            return self::response(null,'-2','用户名由2-16位数字或字母、汉字、下划线组成！');
        }
        if (empty($password)) {
            return self::response(null,'-3','密码为空');
        }
        if (mb_strlen($password,'utf-8') < 1) {
            return self::response(null,'-4','密码必须为大于1位的字符串！');
        }
        if (empty($sex)) {
            return self::response(null,'-5','请选择性别');
        }
        $user = LiveUser::getUserByUserName($name);
        if ($user) {
            return  self::response(null,-6,'用户名已被使用');
        }
        /*if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
            $path = $request->file('avatar')->store('upload','public');
            $avatar = asset('storage/'.$path);
        } else {
            $avatar = '';
        }*/
        $user_avatar = '';
        if (!empty($avatar) && preg_match('/^(data:\s*image\/(\w+);base64,)/', $avatar, $result)) {
            $type = $result[2];
            $file = (string) Str::uuid();
            $filename = $file.".{$type}";
            Storage::disk('public')->put("upload/avatar/{$filename}", base64_decode(str_replace($result[1], '', $avatar)));
            $user_avatar = asset("storage/upload/avatar/{$filename}");
        }
        $flag = LiveUser::createUser([
                'user_name'     => $name,
                'user_password' => $password,
                'user_sex'      => $sex,
                'user_avatar'   => $user_avatar,
                'status'        => $status,
                'created_time'  => time(),
            ]);
        if (!$flag) {
            return  self::response(null,-7,'新建用户失败，请稍后再试哦~');
        }
        return self::response(null,'200');
     }

     public function agentList(Request $request)
     {
         $start_time = $request->input('start_time');
         $end_time   = $request->input('end_time');
         $search     = trim($request->input('search',''));
         $data       = LiveUser::getUserList($start_time,$end_time,$search,1);
         $data->each(function ($item, $key) {
             $item->user_count = $item->user_count;
         });
         return self::response($data,'200');
     }

     public function addAgent(Request $request)
     {
         $name      = $request->input('name');
         $password  = $request->input('password');
         $code      = $request->input('code');
         $phone     = $request->input('phone','');
         $sex       = (int)$request->input('sex');
         $status    = (int)$request->input('status',1);
         $avatar    = $request->input('avatar','');
         if (empty($name)) {
             return self::response(null,'-1','用户名为空');
         }
         if (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u',$name)) {
             return self::response(null,'-2','用户名由2-16位数字或字母、汉字、下划线组成！');
         }
         if (empty($password)) {
             return self::response(null,'-3','密码为空');
         }
         if (mb_strlen($password,'utf-8') < 1) {
             return self::response(null,'-4','密码必须为大于1位的字符串！');
         }
         if (empty($code)) {
             return self::response(null,'-5','邀请码为空');
         }
         if (mb_strlen($code,'utf-8') < 4) {
             return  self::response(null,-6,'邀请码不能少于4位哦');
         }
         if (mb_strlen($code,'utf-8') > 20) {
             return  self::response(null,-7,'邀请码不能大于20位哦');
         }
         if (!empty($phone) && mb_strlen($phone,'utf-8') > 50) {
             return self::response(null,-8,'联系方式的位数不能大于20位哦');
         }
         if (empty($sex)) {
             return self::response(null,'-9','请选择性别');
         }
         $flag1 = LiveUser::getUserIDByInviteCode($code);
         if ($flag1) {
             return self::response(null,-10,'邀请码已被使用了哦~');
         }
         $flag2 = LiveUser::getUserByUserName($name);
         if ($flag2) {
             return  self::response(null,-11,'用户名已被使用');
         }
         /*if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
             $path = $request->file('avatar')->store('upload','public');
             $avatar = asset('storage/'.$path);
         } else {
             $avatar = '';
         }*/
         $user_avatar = '';
         if (!empty($avatar) && preg_match('/^(data:\s*image\/(\w+);base64,)/', $avatar, $result)) {
             $type = $result[2];
             $file = (string) Str::uuid();
             $filename = $file.".{$type}";
             Storage::disk('public')->put("upload/avatar/{$filename}", base64_decode(str_replace($result[1], '', $avatar)));
             $user_avatar = asset("storage/upload/avatar/{$filename}");
         }
         $flag = LiveUser::createUser([
             'user_name'     => $name,
             'user_password' => $password,
             'user_sex'      => $sex,
             'user_phone'    => $phone,
             'user_avatar'   => $user_avatar,
             'is_agent'      => 1,
             'invite_code'   => $code,
             'status'        => $status,
             'created_time'  => time(),
         ]);
         if (!$flag) {
             return  self::response(null,-12,'新建用户失败，请稍后再试哦~');
         }
         return self::response(null,'200');
     }

     public function recharge(Request $request)
     {
         $id    = (int)$request->input('id');
         $score = $request->input('score',0);
         if (empty($id)) {
             return  self::response(null,-1,'请选择要充值的代理哦~');
         }
         if (empty($score)) {
             return  self::response(null,-2,'请输入要充值的积分哦~');
         }
         if (!preg_match('/^[1-9]\d*/',$score)) {
             return  self::response(null,-3,'积分必须是大于0的正整数哦~');
         }
         $flag1 = LiveUser::modifyScore($id,$score,1);
         if (!$flag1) {
             return  self::response(null,-4,'充值积分失败，请稍后再试哦~');
         }
         $flag2 = LiveScoreWater::createWater($id,$score,4);
         if (!$flag2) {
             return  self::response(null,-5,'创建积分记录失败，请稍后再试哦~');
         }
         return self::response(null,'200');
     }

     public function edit(Request $request)
     {
         $id        = (int)$request->input('id');
         $password  = $request->input('password','');
         $code      = $request->input('code','');
         $phone     = $request->input('phone','');
         $sex       = (int)$request->input('sex');
         $status    = (int)$request->input('status',1);
         $avatar    = $request->input('avatar','');
         if (empty($id)) {
             return self::response(null,'-1','请选择要编辑的代理哦~');
         }
         if (!empty($password)) {
             if (mb_strlen($password,'utf-8') < 1) {
                 return self::response(null,'-2','密码必须为大于1位的字符串！');
             }
         }
         if (empty($code)) {
             return self::response(null,'-3','邀请码为空');
         }
         if (mb_strlen($code,'utf-8') < 4) {
             return  self::response(null,-4,'邀请码不能少于4位哦');
         }
         if (mb_strlen($code,'utf-8') > 20) {
             return  self::response(null,-5,'邀请码不能大于20位哦');
         }
         if (!empty($phone) && mb_strlen($phone,'utf-8') > 50) {
             return self::response(null,-6,'联系方式的位数不能大于20位哦');
         }
         if (empty($sex)) {
             return self::response(null,'-7','请选择性别');
         }
         $flag1 = LiveUser::getUserIDByInviteCode($code);
         if ($flag1) {
             return self::response(null,-8,'邀请码已被使用了哦~');
         }
         $user_avatar = '';
         if (!empty($avatar) && preg_match('/^(data:\s*image\/(\w+);base64,)/', $avatar, $result)) {
             $type = $result[2];
             $file = (string) Str::uuid();
             $filename = $file.".{$type}";
             Storage::disk('public')->put("upload/avatar/{$filename}", base64_decode(str_replace($result[1], '', $avatar)));
             $user_avatar = asset("storage/upload/avatar/{$filename}");
         }
         $flag2 = LiveUser::updateUser($id,[
                     'user_password' => $password,
                     'user_sex'      => $sex,
                     'user_phone'    => $phone,
                     'user_avatar'   => $user_avatar,
                     'is_agent'      => 1,
                     'invite_code'   => $code,
                     'status'        => $status,
                 ]);
         if (!$flag2) {
             return  self::response(null,-9,'更新代理失败，请稍后再试哦~');
         }
         return self::response(null,'200');
     }

     public function subordinate(Request $request)
     {
         $id = (int)$request->input('id');
         if (empty($id)) {
             return self::response(null,-1,'请选择要查看的代理哦~');
         }
         $data = LiveUser::getUserListByAgentId($id);
         return self::response($data,'200');
     }
}
